package com.isyscore.os.metadata.common;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isyscore.boot.mybatis.PageRequest;
import com.isyscore.os.core.exception.DataFactoryException;
import com.isyscore.os.core.exception.ErrorCode;
import com.isyscore.os.metadata.common.page.PageParamParser;
import org.springframework.jdbc.BadSqlGrammarException;


/**
 * @author wan.yu
 */
public class CommonService<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {

    public static final String UNKNOWN_COLUMN = "Unknown column";
    public static final String IN_ORDER = "in 'order clause'";
    public static final String APOSTROPHE = "'";
    private PageParamParser<T> pageParamParser = new PageParamParser<>();

    /**
     * 分页数据查询，会根据PageParam中的QueryField注解自动构造QueryWrapper
     *
     * @param pageQuery 分页参数
     * @return
     */
    public IPage<T> pageWithPageParam(PageRequest pageQuery) {
        if (pageQuery == null) {
            pageQuery = new PageRequest();
        }
        QueryWrapper<T> qw = pageParamParser.parsePageParam(pageQuery);
        Page<T> page = pageQuery.toPage();
        if (pageQuery.getOrders() == null || pageQuery.getOrders().isEmpty()) {
            page.addOrder(OrderItem.desc("id"));
        }
        IPage<T> res = new Page<>();
        try {
            res = this.page(page, qw);
        } catch (BadSqlGrammarException e) {
            String message = e.getMessage();
            if (StrUtil.isNotBlank(message) && message.contains(UNKNOWN_COLUMN) && message.contains(IN_ORDER)) {
                String errorColumn = StrUtil.removeAll(StrUtil.subBetween(message,UNKNOWN_COLUMN,IN_ORDER),APOSTROPHE);
                log.error(e.getMessage(),e);
                throw new DataFactoryException(ErrorCode.UNKNOWN_ORDER_COLUMN, errorColumn);
            }
        }
        return res;
    }

}
